package com.gljx.web.service.impl;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.ActitiviUtil;
import com.gljx.util.GetFid;
import com.gljx.web.Entity.MaintainItemAdd;
import com.gljx.web.Entity.MaintainItemAddEntry;
import com.gljx.web.Entity.Message;
import com.gljx.web.Entity.User;
import com.gljx.web.dao.CommonDao;
import com.gljx.web.dao.MaintainItemAddEntryMapper;
import com.gljx.web.dao.MaintainItemAddMapper;
import com.gljx.web.service.MaintainItemAddService;
import com.gljx.web.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class MaintainItemAddServiceImpl extends CommonDao implements MaintainItemAddService{

	//导入activiti工具
	ActitiviUtil activitiUtil = new ActitiviUtil();
	@Autowired
	private MaintainItemAddMapper maintainItemAddMapper;
	@Autowired
	private MaintainItemAddEntryMapper maintainItemAddEntryMapper;
	@Autowired
	private MessageService messageService;
	/**
	 *取分页数据 
	 *@param pindex 页码
	 *@param psql SQL语句，需要带 rownum rn 例如：select rownum rn,t.* from zzda t
	 *@param psize 每页记录数
	 * */
	@Override
	public Map<String, Object> selectPage(int pindex, String psql, int psize) {
		  Map<String, Object> paramMap = new HashMap<String, Object>();
	       paramMap.put("Pindex", pindex);
	       paramMap.put("Psql", psql);
	       paramMap.put("Psize", psize);
	       paramMap.put("Pcount", oracle.jdbc.OracleTypes.INTEGER);
	       paramMap.put("v_cur", oracle.jdbc.OracleTypes.CURSOR);
	       this.getSqlSession().select("com.gljx.web.dao.MaintainItemAddMapper.pagemap", paramMap, null);
	       return  paramMap;
	}

	/**
	 * 取记录总数      dmz 20160921
	 * @param psql   SQL语句
	 * @return
	 */
	@Override
	public Map<String, Object> selectPageCount(String psql) {
		   Map<String, Object> paramMap = new HashMap<String, Object>();
	       paramMap.put("Psql", psql);
	       paramMap.put("Pcount", oracle.jdbc.OracleTypes.INTEGER);
	       this.getSqlSession().select("com.gljx.web.dao.MaintainItemAddMapper.pagecount", paramMap, null);
	       return paramMap;
	}

	/**
	 * 根据条件查询子类信息
	 */
	@Override
	public List<MaintainItemAddEntry> queryMaintainItemAddEntry(String fparentId, String name, String carNumber) {
		// TODO Auto-generated method stub
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("v_fparentid", fparentId);
		paramMap.put("v_name", name);
	    paramMap.put("v_carNumber", carNumber);
		paramMap.put("v_cursor", oracle.jdbc.OracleTypes.CURSOR);
		this.getSqlSession().select("com.gljx.web.dao.MaintainItemAddEntryMapper.selectMaintainItemAddEntry", paramMap, null);
		 @SuppressWarnings("unchecked")
		 List<MaintainItemAddEntry> maintainItemAddEntries = (List<MaintainItemAddEntry>) paramMap.get("v_cursor");
		return maintainItemAddEntries;
	}

	/**
	 * 添加或修改
	 */
	@Override
	public void editMaintainItemAdd(MaintainItemAdd maintainItemAdd, String[] fseq, String[] cfminame,
			String[] carfnumber, String[] carid, String[] cfmibxq, String[] cfmigs, String[] cfmidj, String[] cfmims,
			User user, String time) {
		// TODO Auto-generated method stub
		if("".equals(maintainItemAdd.getFid()) || maintainItemAdd.getFid() == null){
			//创建人id
			maintainItemAdd.setFcreatorid(user.getFid());
			//利用UUID生成fid
			maintainItemAdd.setFid(GetFid.UUIDIntoFid());
			//当前时间
			maintainItemAdd.setFcreatetime(time);
			//状态
            maintainItemAdd.setCfbillstate(3L);
            //添加
			maintainItemAddMapper.insertSelective(maintainItemAdd);
		}else{
			//修改时间时间
			maintainItemAdd.setFlastupdatetime(time);
			//修改人id
			maintainItemAdd.setFlastupdateuserid(user.getFid());
			//修改
			maintainItemAddMapper.updateByPrimaryKeySelective(maintainItemAdd);
			//先删除子类信息
			maintainItemAddEntryMapper.deleteByFparentId(maintainItemAdd.getFid());
		}
		//添加
		List<MaintainItemAddEntry> maintainItemAddEntrys = new ArrayList<>();
		if(fseq ==null || fseq.length == 0){
			
		}else{
			for (int i = 0; i < fseq.length; i++) {
				MaintainItemAddEntry maintainItemAddEntry = new MaintainItemAddEntry();
				maintainItemAddEntry.setCfminame(cfminame[i]);
				maintainItemAddEntry.setCarfnumber(carfnumber[i]);
				maintainItemAddEntry.setCarid(carid[i]);
				maintainItemAddEntry.setCfmibxq(cfmibxq[i]);
				if("".equals(cfmigs[i])){
					
				}else{
					maintainItemAddEntry.setCfmigs(new BigDecimal(cfmigs[i]));
				}
				if("".equals(cfmidj[i])){
					
				}else{
					maintainItemAddEntry.setCfmidj(new BigDecimal(cfmidj[i]));
				}
				maintainItemAddEntry.setCfmims(cfmims[i]);
				maintainItemAddEntry.setFseq((long)i+1);
				maintainItemAddEntry.setFid(GetFid.UUIDIntoFid());
				maintainItemAddEntry.setFparentid(maintainItemAdd.getFid());
				maintainItemAddEntrys.add(maintainItemAddEntry);
			}
			maintainItemAddEntryMapper.insertMaintainItemAddEntry(maintainItemAddEntrys);
		}
	}

	/**
	 * 根据fid查询
	 */
	@Override
	public MaintainItemAdd queryMaintainItemAddByFid(String fid) {
		// TODO Auto-generated method stub
		return maintainItemAddMapper.selectMaintainItemAddByFid(fid);
	}

	/**
	 * 根据fid删除
	 */
	@Override
    public void deleteMaintainItemAddByFid(User user,String fid, String[] deleteId, String[] fnumber, String fnumber2) {
        // TODO Auto-generated method stub
		if(fid == null || "".equals(fid)){
            /*//先删除子类信息
            maintainItemAddEntryMapper.deleteByArray(deleteId);
			//在删除父类信息
			maintainItemAddMapper.deleteByArray(deleteId);*/
            for (int i = 0; i < deleteId.length; i++) {
                //先删除子类信息
                maintainItemAddEntryMapper.deleteByFparentId(deleteId[i]);
                //在删除父类信息
                maintainItemAddMapper.deleteByPrimaryKey(deleteId[i]);
                //删除流程
                activitiUtil.deleteTask(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MAINTAININTEM_KEY_GL : ActivitiKey.MAINTAININTEM_KEY_NC, fnumber[i]);
            }
            //删除流程
		}else{
			//先删除子类信息
			maintainItemAddEntryMapper.deleteByFparentId(fid);
			//在删除父类信息
			maintainItemAddMapper.deleteByPrimaryKey(fid);
            //删除流程
            activitiUtil.deleteTask(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MAINTAININTEM_KEY_GL : ActivitiKey.MAINTAININTEM_KEY_NC, fnumber2);
        }
	}

	/**
	 * 审核，反审核
	 */
	@Override
    public int auditMaintainItemAdd(User user,String fid, String type, String fhandlerId, String fnumber, String message, String state, String auditState) {
        // TODO Auto-generated method stub
		MaintainItemAdd maintainItemAdd = new MaintainItemAdd();

		if ("1".equals(type)) {
			//VariableName  流程变量名称  fnumber 单据；state 状态 同意，不同意，前段传来的备注
			String message2;
			if ("".equals(message)) {
				if ("1".equals(state)) {
					message2 = "同意";
				} else {
					message2 = "不同意";
				}
			} else {
				if ("1".equals(state)) {
					message2 = "同意:" + message;
				} else {
					message2 = "不同意：" + message;
				}
			}
			Object returnMsg = activitiUtil.auditComplteMessage(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MAINTAININTEM_KEY_GL : ActivitiKey.MAINTAININTEM_KEY_NC, fnumber, Integer.valueOf(state), message2);
			if (returnMsg instanceof Message) {
				Message resultMsg = (Message) returnMsg;
				resultMsg.setMessage("添加维修项目-审核 #" + fnumber + " #");//消息内容
				resultMsg.setUrl("/queryMaintainItemAddByFid?fid=" + fid + "");//详细路径
				messageService.insert(resultMsg);
				//判断是否同意,如果不同意,修改状态
				if (!"1".equals(state)) {
					//fid
					maintainItemAdd.setFid(fid);
					//状态
					maintainItemAdd.setCfbillstate(3L);
					//修改
					maintainItemAddMapper.updateByPrimaryKeySelective(maintainItemAdd);
				}
			} else if (activitiUtil.notAssign.equals(returnMsg)) {
				System.out.println("当前用户不是要求的经办人");
				return 3;
			} else if (activitiUtil.FINISH.equals(returnMsg)) {
				System.out.println("此流程成功推进,并且此流程已经结束");
				//fid
				maintainItemAdd.setFid(fid);
				//操作人id
				maintainItemAdd.setFauditorid(fhandlerId);
				//修改人
				maintainItemAdd.setFlastupdateuserid(fhandlerId);
				//状态
				maintainItemAdd.setCfbillstate(5L);
				return maintainItemAddMapper.updateByPrimaryKeySelective(maintainItemAdd);
			} else if (activitiUtil.SUCCESS.equals(returnMsg)) {
				System.out.println("此流程成功推进");
				//判断是否同意,如果不同意,修改状态
				if (!"1".equals(state)) {
					//fid
					maintainItemAdd.setFid(fid);
					//状态
					maintainItemAdd.setCfbillstate(3L);
					//修改
					maintainItemAddMapper.updateByPrimaryKeySelective(maintainItemAdd);
				}
				return 0;
			} else if (activitiUtil.notTask.equals(returnMsg)) {
				System.out.println("没有找到正在进行的相关流程");
				return 2;
			}
		} else {
            if ("endTrue".equals(auditState)) {
                Message message2 = activitiUtil.getMessage(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MAINTAININTEM_KEY_GL : ActivitiKey.MAINTAININTEM_KEY_NC, fnumber);
                if (message2 != null) {
					message2.setMessage("添加维修项目-反审核 #" + fnumber + " #");//消息内容
					message2.setUrl("/queryMaintainItemAddByFid?fid=" + fid + "");//详细路径
                    messageService.insert(message2);
                }
            } else {
                Object result = activitiUtil.jumpActivtiMessage(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MAINTAININTEM_KEY_GL : ActivitiKey.MAINTAININTEM_KEY_NC, fnumber, message);
                if (result instanceof Message) {
                    Message resultMsg = (Message) result;
					resultMsg.setMessage("添加维修项目-反审核" + fnumber + " #");//消息内容
					resultMsg.setUrl("/queryMaintainItemAddByFid?fid=" + fid + "");//详细路径
                    messageService.insert(resultMsg);
                }
            }
            //单据状态
            maintainItemAdd.setCfbillstate(3L);
            //fid
            maintainItemAdd.setFid(fid);
            //操作人id
            maintainItemAdd.setFauditorid(fhandlerId);
            //修改人
            maintainItemAdd.setFlastupdateuserid(fhandlerId);
            return maintainItemAddMapper.updateByPrimaryKeySelective(maintainItemAdd);
        }
		return 0;
	}

    @Override
    public int modifyMaintainItemAdd(MaintainItemAdd maintainItemAdd) {
        return maintainItemAddMapper.updateByPrimaryKeySelective(maintainItemAdd);
    }

    @Override
    public List<MaintainItemAddEntry> selectMaintainItemAddByInfo(String fcompanyid, String name, String carNumber, String beginTime, String endTime, String fnumber) {
        Map<String, String> map = new HashMap<>();
        map.put("fcompanyid", fcompanyid);
        map.put("name", name);
        map.put("carNumber", carNumber);
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("fnumber", fnumber);
        return maintainItemAddEntryMapper.selectMaintainItemAddByInfo(map);
    }
}
